package cz.hanis.android.pubaccounting;

import java.util.List;

import cz.hanis.android.pubaccounting.app.PubAccountingApp;
import cz.hanis.android.pubaccounting.db.DbConstants;
import cz.hanis.android.pubaccounting.db.DbManager;
import cz.hanis.android.pubaccounting.location.LocationHelper;
import cz.hanis.android.pubaccounting.model.Item;
import cz.hanis.android.pubaccounting.model.Pub;
import cz.hanis.android.pubaccounting.tools.DataHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PubEditingActivity extends Activity {

	public static final String PUB_ID_KEY = "pub_id";

	public static final int NEW = 0;
	public static final int EDIT = 1;

	private DbManager dbManager;

	private Handler handler;
	private LocationManager locationMgr;

	private Pub pub;
	private int type;

	private EditText nameEdit;
	private EditText addressEdit;
	private EditText homepageEdit;
	private EditText longitudeEdit;
	private EditText latitudeEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pub_editing);

		dbManager = ((PubAccountingApp) getApplication()).getDbManager();
		locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		nameEdit = (EditText) findViewById(R.id.pub_editing_name);
		addressEdit = (EditText) findViewById(R.id.pub_editing_address);
		homepageEdit = (EditText) findViewById(R.id.pub_editing_homepage);
		latitudeEdit = (EditText) findViewById(R.id.pub_editing_latitude);
		longitudeEdit = (EditText) findViewById(R.id.pub_editing_longitude);

		handler = new Handler() {
			public void handleMessage(Message m) {
				Log.d(LocationHelper.LOG_TAG, "Handler returned with message: "
						+ m.toString());
				if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_FOUND) {
					Log.d("deb", String.valueOf(m.arg1));
					latitudeEdit.setText(String.valueOf(m.arg1));
					longitudeEdit.setText(String.valueOf(m.arg2));
				} else if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_NULL) {
					showWarningDialog("Varování", "Unable to get location.",
							"Ok");
				} else if (m.what == LocationHelper.MESSAGE_CODE_PROVIDER_NOT_PRESENT) {
					showWarningDialog("Varování", "Provider not present.", "Ok");
				}
			}
		};

		Button getLoc = (Button) findViewById(R.id.pub_editing_get_loc);
		getLoc.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!locationMgr
						.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
					ProviderUnavailableDialog();

				} else {
					LocationHelper locationHelper = new LocationHelper(
							locationMgr, handler);
					// here we aren't using a progressdialog around
					// getCurrentLocation
					// (don't want to block entire UI)
					// (but be advised that you could if the situation
					// absolutely
					// required it)
					locationHelper.getCurrentLocation(30);
				}
			}
		});

		Button saveButton = (Button) findViewById(R.id.pub_editing_save);
		saveButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				save();
			}
		});
		long pubId = getIntent()
				.getLongExtra(PubEditingActivity.PUB_ID_KEY, -1);
		if (pubId == -1) {
			this.type = NEW;
			this.pub = new Pub();
			return;
		} else {
			this.type = EDIT;
			pub = dbManager.getPub(pubId);
			applyPub(pub);
		}
	}

	private void applyPub(Pub pub) {
		nameEdit.setText(pub.getName());
		addressEdit.setText(pub.getAddress());
		homepageEdit.setText(pub.getHompage());
		longitudeEdit.setText(String.valueOf(pub.getLongitude()));
		latitudeEdit.setText(String.valueOf(pub.getLatitude()));
		createItemsList(pub.getItems());
	}

	private void createItemsList(List<Item> items) {
		LinearLayout box = (LinearLayout) findViewById(R.id.pub_editing_item_box);
		for (Item item : items) {
			LinearLayout itemLayout = new LinearLayout(this);
			itemLayout.setOrientation(LinearLayout.HORIZONTAL);
			itemLayout.setLayoutParams(new LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));

			TextView nameView = new TextView(this);
			nameView.setText(item.getName());
			nameView.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			Log.d("cost info", String.valueOf(item.getCost()));

			TextView costView = new TextView(this);
			costView.setText(String.valueOf(item.getCost()));
			costView.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			// costView.setTextColor(R.color.red);
			costView.setPadding(10, 0, 0, 0);

			itemLayout.addView(nameView);
			itemLayout.addView(costView);
			box.addView(itemLayout);
		}
	}

	private Pub parsePub() throws InputParsingException {
		String name = nameEdit.getText().toString();
		if ("".equals(name)) {
			throw new InputParsingException("Název není zadán.");

		}
		String address = addressEdit.getText().toString();
		String homepage = homepageEdit.getText().toString();
		String longitudeString = longitudeEdit.getText().toString();
		String latitudeString = latitudeEdit.getText().toString();

		double longitude = 0;
		if (!"".equals(longitudeString)) {
			try {
				longitude = Double.parseDouble(longitudeString);
			} catch (NumberFormatException ex) {
				throw new InputParsingException(
						"Longitude musí být reálné číslo");
			}
		}
		double latitude = 0;
		if (!"".equals(latitudeString)) {
			try {
				latitude = Double.parseDouble(latitudeString);
			} catch (NumberFormatException ex) {
				throw new InputParsingException(
						"Latitude musí být reálné číslo");
			}
		}
		pub.setName(name);
		pub.setAddress(address);
		pub.setHompage(homepage);
		pub.setLatitude(latitude);
		pub.setLongitude(longitude);
		return pub;
	}

	private void save() {
		try {
			parsePub();
		} catch (InputParsingException e) {
			showWarningDialog("Varování", e.getMessage(), "Ok");
			return;
		}
		switch (type) {
		case NEW:
			dbManager.savePub(pub);
			break;
		case EDIT:
			dbManager.updatePub(pub);
			break;
		}
		// Log.d("onSaveClick" ,"--" + nameEdit.getText() + "--");
		finish();
	}

	private void showWarningDialog(String title, String message, String button) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(title);
		dialog.setMessage(message);
		dialog.setPositiveButton(button, null);
		dialog.show();
	}

	private void ProviderUnavailableDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("GPS is not enabled")
				.setMessage(
						"Would you like to go the location settings and enable GPS?")
				.setCancelable(true)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								startActivity(new Intent(
										Settings.ACTION_SECURITY_SETTINGS));
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

	}

}
